package com.ny.dao.impl;

import com.ny.dao.OrderDao;
import com.ny.entity.Order;
import com.ny.entity.Product;
import com.ny.until.SqlConnection;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class OrderDaoImpl implements OrderDao {
    Connection connection = SqlConnection.getCon();

    public OrderDaoImpl() throws ClassNotFoundException, SQLException {
    }

    private Product findProductById(int productId) {
        return null;
    }

    @Override
    public int addOrder(Order order) throws SQLException, ClassNotFoundException {
        String sql = "insert into orders (student_id,product_id,number,total_price) values(?,?,?,?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1, order.getStudentId());
        preparedStatement.setInt(2, order.getProductId());
        preparedStatement.setInt(3, order.getNumber());
        preparedStatement.setDouble(4, order.getTotalPrice());
        return preparedStatement.executeUpdate();
    }

    @Override
    public List<Order> findAllOrder() throws SQLException {
        String sql = "select * from orders";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();
        List<Order> orderList = new ArrayList<>();
        while (resultSet.next()) {
            Order order = new Order();
            order.setOrderId(resultSet.getInt("order_id"));
            order.setStudentId(resultSet.getInt("student_id"));
            order.setProductId(resultSet.getInt("product_id"));
            order.setNumber(resultSet.getInt("number"));
            order.setTotalPrice(resultSet.getDouble("total_price"));
            orderList.add(order);
        }
        return orderList;
    }

    @Override
    public boolean updateOrder(int orderId, int number) throws SQLException {
        String sql = "update orders set number = ? where order_id = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1, number);
        preparedStatement.setInt(2, orderId);
        int rowsAffected = preparedStatement.executeUpdate();
        return rowsAffected > 0;
    }

    @Override
    public boolean deleteOrder(int orderId) throws SQLException {
        String sql = "delete from orders where order_id = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1, orderId);
        return preparedStatement.executeUpdate() > 0;
    }

}


